# -*- coding:utf-8 -*-
from __future__ import absolute_import
from django.shortcuts import render, render_to_response, redirect
from django.contrib.gis import forms
from django.template import RequestContext
from django.http import HttpResponseRedirect,HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from ratelimit.decorators import ratelimit
from datakeeper.models import *
from datakeeper.utils import *
from weblib.django.setting import *
from .models import *
from .workers import *
from .css_templates import *


# @login_required
@csrf_protect
def main_page(request):
    user = request.user
    mods = WrasModule.objects.filter(enabled=True)
    accessible_mods = []
    accessible_tool_panes = []

    # for mod in mods:
    #     if mod.public or module_perm_checker.can_use(user, mod):
    #         accessible_mods.append(mod)

    system_info = {
        "name": ""
    }
    system_info_more = get_setting('SYSTEM_INFO', {})
    system_info.update(system_info_more)
    misc_info = {
        "project_tab_class": "",
        "project_tab_name": u"工程",
    }
    misc_info_more = get_setting('MISC_INFO', {})
    misc_info.update(misc_info_more)

    help_items = get_setting('HELP_ITEMS', [])

    context = RequestContext(request, {
        'user': user,
        'is_developer': user.groups.filter(name='Developer').exists(),
        'debug': get_setting('DEBUG', False),
        'mods': accessible_mods,
        'system_info': system_info,
        'misc_info': misc_info,
        'help_items': help_items
    })
    return render_to_response('fengge/main.html', context)


def help_page(request, topic=None):
    # raw_pages = {
    #     None: 'fengge/help.html',
    #     'about_datasets': 'fengge/about_datasets.html',
    #     'about_formats': 'fengge/about_formats.html',
    #     'about_register': 'fengge/about_register.html',
    #     'about_browser': 'fengge/about_browser.html',
    #     'project': 'fengge/project.html',
    #     'ui': 'fengge/ui.html',
    #     'map_feature': 'fengge/map_feature.html',
    #     'map_widget': 'fengge/map_widget.html',
    # }
    use_cab = get_setting('HELP_PAGE_USE_CAB', False)
    if use_cab:
        try:
            pass
            ##help_cab = Cabinet.objects.get(pk='help')
           # topic = topic.rstrip('/') if topic else 'help'
            #topic_ext = get_ext(topic)
            #if topic_ext == '':
            #    topic_file_path = '%s.html' % topic
            #else:
            #    topic_file_path = topic
           # #true_path = help_cab.get_file(topic_file_path)
           # return HttpResponse(open(true_path).read())
        except Exception as e:
            raise Http404
    else:
        if topic:
            topic = topic.rstrip('/')
            raw_page = 'help/%s.html' % topic
        else:
            raw_page = 'help/help.html'
        context = RequestContext(request, {'user': request.user, 'topic': topic})

        return render_to_response(raw_page, context)


def login_page(request):
    context = {}
    return render_to_response('dxuser/login.html', context)


# 将废弃, 由mod_resource_view代替.
# @login_required
@csrf_protect
def mod_view(request, modname, resource, *args, **kwargs):
    try:
        mod = WrasModule.objects.get(name=modname)

        # if not mod.public and not module_perm_checker.can_use(request.user, mod):
        #     return HttpResponseForbidden(u'User %s cannot use module %s' % (request.user, mod))

        mod_dir = 'wrasmods/%s' % mod.name

        resource_path = '%s/%s' % (mod_dir, resource)
        if not os.path.exists(resource_path):
            raise Http404

        return file_response(resource_path)
    except WrasModule.DoesNotExist:
        raise Http404


# @login_required
@csrf_protect
def mod_resource_view(request, modname, resource, *args, **kwargs):
    try:
        mod = WrasModule.objects.get(name=modname)

        # if not mod.public and not module_perm_checker.can_use(request.user, mod):
        #     return HttpResponseForbidden(u'User %s cannot use module %s' % (request.user, mod))

        mod_dir = 'wrasmods/%s' % mod.name

        if resource.startswith('/'):
            return HttpResponseRedirect(resource)
        else:
            resource_path = '%s/resource/%s' % (mod_dir, resource)
            if not os.path.exists(resource_path):
                raise Http404

            if resource_path.endswith('.js'):
                if request.user.groups.filter(name='Developer').exists():
                    return file_response(resource_path)
                else:
                    min_path = re.sub(r'\.js$', '.min.js', resource_path)
                    if os.path.exists(min_path):
                        return file_response(min_path)
                    min_path = re.sub(r'\.js$', '-min.js', resource_path)
                    if os.path.exists(min_path):
                        return file_response(min_path)
                    with open(resource_path) as jsfile:
                        try:
                            pass
                     #       js = jsmin(jsfile.read())
                     #       return string_response(js, save_name=BASENAME(resource_path), content_type='text/javascript')
                        except Exception as e:
                            return ExceptionJsonResponse({"reason": repr(e)})
            else:
                return file_response(resource_path)
    except WrasModule.DoesNotExist:
        raise Http404


def per_day_data_rate(group, request):
    try:
        user_setting = UserDataSetting.objects.get(user=request.user)
    except UserDataSetting.DoesNotExist:
        return '100/d'

    if user_setting.data_limit_per_day < 0:
        return None
    else:
        return '%d/d' % user_setting.data_limit_per_day


# @login_required
@csrf_protect
def lookup_view(request, *args, **kwargs):
    return data_keeper.lookup_view(request, *args, **kwargs)

# @ratelimit(key='user', rate='1/1s', block=True)
# @login_required
@csrf_protect
@ratelimit(key='user', rate=per_day_data_rate, block=True)
def data_view(request, uri, *args, **kwargs):
    return data_keeper.data_view(request, uri, *args, **kwargs)


class FakePricer(object):
    def get_price(self, uri):
        return 50.0

pricer = FakePricer()


# @login_required
@csrf_protect
@ratelimit(key='user', rate=per_day_data_rate, block=True)
def fake_buy_view(request, uri, *args, **kwargs):
    user_owns_it = user_owns_data(request.user, uri)
    if user_owns_it:
        return JsonResponse({
            "type": "BuyResult",
            "uri": uri,
            "result": "no_need"
        })

    price = pricer.get_price(uri)
    accounts = request.user.accounts.order_by('priority')
    pay_list = []
    remaining_price = price
    for account in accounts:
        if account.amount >= 0.0:
            this_price = min(remaining_price, account.amount)
            pay_list.append((account, this_price))
            remaining_price -= this_price

            if remaining_price <= 0.0:
                break

    if remaining_price > 0.0:
        return JsonResponse({
            "type": "BuyResult",
            "uri": "uri",
            "result": "failed"
        })

    for account, this_price in pay_list:
        pass
        #try:
          #  sys_account = Account.objects.filter(user=clean_user('admin')).get(type=account.type)
           # transfer(account, sys_account, this_price, cause=uri)
           # user_data_key = get_user_data_key(request.user, uri)
          #  u_d = User_Data(pk=user_data_key)
          #  u_d.save()
          #  return JsonResponse({
          #      "type": "BuyResult",
          #      "uri": uri,
          #      "result": "succeeded"
          #  })
        #except Account.DoesNotExist:
        #    return JsonResponse({
        #        "type": "BuyResult",
        #        "uri": "uri",
        #        "result": "failed"
        #    })


# @login_required
@csrf_protect
@ratelimit(key='user', rate=per_day_data_rate, block=True)
def fake_price_view(request, uri, *args, **kwargs):
    return JsonResponse({
        "type": "PriceResult",
        "uri": uri,
        "result": pricer.get_price(uri)
    })


def get_invite_code_view(request, *args, **kwargs):
    if request.method != 'POST':
        return HttpResponseRedirect('/user/login/')

    p = request.POST
    if p['email']:
       # send_email_to_user(user='admin', context={
        #    'title': u'索要邀请码',
        #    'msg': u'有客户来索要邀请码, 请审核: \n姓名: %s\n邮箱: %s\n电话: %s\n公司: %s\n职务: %s' % (p['name'], p['email'], p['phone'], p['company'], p['position'])
        #})
        return HttpResponseRedirect('/wait_invite/?email=%s' % p['email'])
    else:
        return HttpResponseRedirect('/wait_invite/')

def wait_invite_view(request, *args, **kwargs):
    email = request.GET.get('email', '')
    return render(request, 'fengge/wait_invite.html', context={"email": email})


def css_view(request, css_type, *args, **kwargs):
    css_type = css_type.rstrip('/')
    if css_type == 'system':
        res_list = []
        for style in WrasStyle.objects.filter(enabled=True):
            res_list.append(style.css)
        css = '\n\n'.join(res_list)
    else:
        if css_type == 'project':
            tmpl = css_project_template
         #   ptypes = [ptype.name for ptype in WrasProjectType.objects.all()]
         #   context = {'ptypes': ptypes}
        elif css_type == 'datasets':
            tmpl = css_datasets_template
            datasets = [ds for ds in DataSet.objects.all() if user_can_access_dataset(request.user, ds)]
            ds_names = [ds.name for ds in datasets]
            ss_names = set()
            varnames = set()
            for ds in datasets:
                ds_obj = ds.dataset
                for ss in ds_obj.uri_subsets.keys():
                    ss_names.add(ss)

                schema = ds_obj.get_schema(request)
                ss_subs = schema.get('subs', None)
                if not ss_subs:
                    continue

                for ss_sub in ss_subs:
                    var_subs = ss_sub.get('subs', None)
                    if not var_subs:
                        continue
                    for var_sub in var_subs:
                        varnames.add(var_sub['name'])
            ss_names = sorted(list(ss_names))
            varnames = sorted(list(varnames))
            context = {'datasets': ds_names, 'subsets': ss_names, 'variables': varnames}
        else:
            raise Http404

        css = tmpl.render(**context)

    return string_response(css, save_name='%s.css' % css_type)

